package com.tomvian.base 
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.system.Capabilities;
	import flash.utils.getDefinitionByName;
	
	/**
	 * Preloader
	 * @author Thomas Vian
	 */
	public class Preloader extends MovieClip
	{
		//--------------------------------------------------------------------------
		//
		//  Properties
		//
		//--------------------------------------------------------------------------
		
		protected var _graphics:MovieClip;
		protected var _loadDisplay:MovieClip;
		
		protected var _mainClass:String;
		
		//--------------------------------------------------------------------------
		//
		//  Getters / Setters
		//
		//--------------------------------------------------------------------------
		
		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		
		public function Preloader(mainClass:String, graphics:MovieClip) 
		{
			_mainClass = mainClass;
			_graphics = graphics;
			addChild(_graphics);
			
			if(_graphics.loadDisplay) _loadDisplay = _graphics.loadDisplay;
			
			Domain.checkDomain(this);
			
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------
		
		protected function onEnterFrame(e:Event):void
		{
			if (framesLoaded != totalFrames) 	updateLoader(root.loaderInfo.bytesLoaded / root.loaderInfo.bytesTotal);
			else  								onLoaded();
		}
		
		protected function updateLoader(percent:Number):void
		{
			if (_loadDisplay) _loadDisplay.gotoAndStop(1 + uint(percent * (_loadDisplay.totalFrames - 1)));
		}
		
		protected function onLoaded():void
		{
			updateLoader(1);
			
			removeEventListener(Event.ENTER_FRAME, onEnterFrame);
			
			nextFrame();
			
			var main:Class = getDefinitionByName(_mainClass) as Class;
			
			if (main) addChild(new main() as DisplayObject);
		}
		
		public function clearLoader():void
		{
			if (_graphics && contains(_graphics)) removeChild(_graphics);
			
			_graphics = null;
			_loadDisplay = null;
		}
		
		public function getVersion():Array
		{
			var version:String = Capabilities.version;
			var vers:Array = version.substring(4).split(",");
			for (var i:uint = 0, l:uint = vers.length; i < l; i++) vers[i] = uint(vers[i]);
			
			return vers;
		}
	}
}